<?php

class subcert extends CActiveRecord {
/**
 * The followings are the available columns in table 'subcert':
 * @var integer $id
 * @var string $out_permit
 * @var string $awb
 * @var string $vessel
 * @var string $remark
 * @var double $etd
 * @var string $mode
 * @var string $packing_id
 */
 public $cargo_details=array(), $ErrorDO=array();
/**
 * Returns the static model of the specified AR class.
 * @return CActiveRecord the static model class
 */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'subcert';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        return array(
        array('remark','safe'),
        array('out_permit','length','max'=>15),
        array('awb','length','max'=>15),
        array('vessel','length','max'=>25),
        array('mode','length','max'=>10),
        array('out_permit, awb, vessel, etd, mode', 'required'),
        array('out_permit','unique','caseSensitive'=>false,'allowEmpty'=>false,'message'=>'Outward Permit alread exists.'),
        array('etd','type','type'=>'date','dateFormat'=>'dd/MM/yyyy'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
        'packing_list'=>array(self::HAS_MANY,'packing_list','subcert_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */

    public function scopes() {
        return array(
        'enquiry'=>array('groupby'=>'out_permit','limit'=>15),
        );
    }
    public function beforeSave() {
        $_date = explode("/", $this->etd);
        $this->etd = mktime(0,0,0,$_date[1],$_date[0],$_date[2]);
        return parent::beforeSave();
    }
    public function afterSave() {
       
        if(count($this->cargo_details)>0) {
            foreach($this->cargo_details as $id=>$value) {
                $model = cargo_details::model()->findByPk($id);
                if($model) {
                    $model->subcert_id = $this->id;
                    $model->save(false);
                }
                else
                    $this->ErrorDO[] = $id;
            }
        }
        return parent::afterSave();
    }
    public function attributeLabels() {
        return array(
        'out_permit'=>'Export Permit',
        'awb'=>'AirWay Bill',
        'vessel'=>'Vessel',
        'remark'=>'Remark',
        'etd'=>'Departure date',
        'mode'=>'Mode',
        );
    }
}